import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'

import Detail from '@/views/Detail'
import Layout from '@/views/Layout'
import Login from '@/views/Login'
import Register from '@/views/Register'

import Article from '@/views/Article'
import Collect from '@/views/Collect'
import Like from '@/views/Like'
import User from '@/views/User'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/article' },
  { path: '/detail/:id', component: Detail },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  },
  { path: '/login', component: Login },
  { path: '/register', component: Register }

]

const router = new VueRouter({
  routes
})
const whiteList = ['/login', '/register']
// 导航守卫 => 全局前置守卫
router.beforeEach((to, from, next) => {
  // 执行时机:每次页面跳转都会触发该函数
  // 只要注册了全局前置守卫,路由会立即瘫痪,必须要调用next方法来放行
  // 参数1 to到哪里去
  // 参数2 from从哪里来
  // 参数3 next函数 决定是否放行 next()表示放行 next('路径')表示强制跳转到指定页面 next(false) 表示不放行
  // next()
  const token = getToken()
  if (token) {
    next()
  } else {
    // if (to.path === '/login' || to.path === '/register')
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Toast.fail('您还未登录,请登录')
      next('/login')
    }
  }
})

export default router
